package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.Admin;
import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.UUID;

@Controller
@RequestMapping("/houseImage")
public class HouseImageController extends BaseController {

    @Reference
    private HouseImageService houseImageService;

    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(@PathVariable Long houseId, @PathVariable Integer type, Model model) {

        model.addAttribute("houseId", houseId);
        model.addAttribute("Type", type);

        return "house/upload";
    }

    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable Long houseId, @PathVariable Integer type, @RequestParam("file") MultipartFile[] files) throws IOException {

        if (files != null && files.length > 0) {
            for (MultipartFile file : files) {
                //上传图片到七牛云
                byte[] bytes = file.getBytes();
                String fileName = UUID.randomUUID().toString();
                String originalFilename = file.getOriginalFilename();
                String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
                fileName += extName;
                QiniuUtil.upload2Qiniu(bytes, fileName);

                //写图片信息
                HouseImage houseImage = new HouseImage();
                houseImage.setHouseId(houseId);
                houseImage.setType(type);
                houseImage.setImageName(file.getOriginalFilename());
                houseImage.setImageUrl("http://renohtnpm.hb-bkt.clouddn.com/" + fileName);
                houseImageService.insert(houseImage);
            }
        }
        return Result.ok();
    }

    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable Long houseId, @PathVariable Long id) {

        HouseImage houseImage = this.houseImageService.getById(id);
//        String fileName = houseImage.getImageUrl().substring(houseImage.getImageUrl().lastIndexOf("/" + 1));
//        QiniuUtil.deleteFileFromQiniu(fileName);

        QiniuUtil.deleteFileFromQiniu(houseImage.getImageUrl());

        this.houseImageService.delete(id);
        return "redirect:/house/" + houseId;
    }
}
